package com.example.loginjwtdemo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Date;

public final class JwtUtil {


    private static final String secretKey = "xxyy";
    private static final Duration duration = Duration.ofHours(2);

    public static String generate(String username){

        Date expireDate = new Date(System.currentTimeMillis()+duration.toMillis());

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512,secretKey)
                .compact();
    }


    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parse(String token){
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {

        }
        return claims;
    }
}
